﻿using System;
using System.Text;
using System.Windows.Forms;
using TCPServerSocket;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private TcpServer _tcp;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _tcp = new TcpServer(); // new server
            _tcp.RecvNewClientAction = client =>
            {
                string str = "recv new client: " + client.ToString() + DateTime.Now;
                this.Invoke(
                    new Action<string>(s => textBox1.AppendText(s + Environment.NewLine)), 
                    new object[] { str });
            };

            _tcp.LostClientAction = client =>
            {
                string str = "lost client: " + client.ToString() + DateTime.Now;
                this.Invoke(
                    new Action<string>(s => textBox1.AppendText(s + Environment.NewLine)),
                    new object[] { str });
            };

            _tcp.RecvDataAction =(ip, data, len) => this.Invoke(
                new Action<string>(s => textBox1.AppendText(ip + s + Environment.NewLine)),
                new object[] { Encoding.ASCII.GetString(data, 0, len) });
            _tcp.StartListen();  //start listen
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            _tcp.StopListen();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            _tcp.SendMessage("192.168.0.110","test");
        }
    }
}
